import config from '../action/config.js'
const cookieParser = require('cookieparser')
export const actions = {
  async nuxtServerInit ({ commit }, { req, $axios }) {
    if (req && req.headers && req.headers.cookie) {
      const cookies = cookieParser.parse(req.headers.cookie)
      const token = cookies[config.default_data.KEY_COOKIE_TOKEN]
      if (token) {
        try {
          // 设置认证信息
          commit('auth/login', token)
          const response = await $axios.$get(config.api.get.User.myInfo)
          if (response.code === 0) {
            // 设置用户信息
            commit('userProfile/setUser', response.data)

            // 获取未读消息数量
            const messageResponse = await $axios.$get(config.api.get.Message.count);
            commit('message/setUnReadCount', messageResponse.data.unReadCount)
          }
        } catch (e) {
          // 请求出错，删除认证信息
          commit('auth/logout')
        }
      }
    }
  }
}
